package com.xjmall.controller.background;

import com.google.common.collect.Maps;
import com.xjmall.common.Const;
import com.xjmall.common.ServerResult;
import com.xjmall.exception.AuthorityException;
import com.xjmall.exception.NotLoginException;
import com.xjmall.pojo.Product;
import com.xjmall.pojo.User;
import com.xjmall.service.IFileService;
import com.xjmall.service.IProductService;
import com.xjmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 后台商品管理Controller
 * Created by An on 2017/5/16.
 */
@Controller
@RequestMapping("/manage/product/")
public class ProductManageController {

    @Autowired
    private IProductService iProductService;
    @Autowired
    private IFileService iFileService;

    /**
     * 保存商品信息
     * @param session 当前会话
     * @param product 待保存的商品信息
     * @return ServerResult
     */
    @RequestMapping(value = "save.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResult saveProduct(HttpSession session, Product product) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.saveOrUpdateProduct(product);
    }

    /**
     * 修改商品销售状态（上下架）
     * @param session 当前会话
     * @param productId 商品id
     * @param status 商品销售状态
     * @return ServerResult
     */
    @RequestMapping(value = "set_sale_status.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResult setSaleStatus(HttpSession session, Integer productId, Integer status) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.setSaleStatus(productId, status);
    }

    /**
     * 获取商品详情
     * @param session 当前会话
     * @param productId 商品id
     * @return ServerResult
     */
    @RequestMapping(value = "detail.do", method = RequestMethod.GET)
    @ResponseBody
    public ServerResult getDetail(HttpSession session, Integer productId) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.getManageProductDetail(productId);
    }

    /**
     * 商品列表
     * @param session 当前会话
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return ServerResult
     */
    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResult getList(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.getProductList(pageNum, pageSize);
    }

    /**
     * 根据搜索条件查询商品列表
     * @param session 当前会话
     * @param productName 搜索的商品名称
     * @param productId 搜索的商品id
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return ServerzResult
     */
    @RequestMapping(value = "search.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResult getSearch(HttpSession session, String productName, Integer productId,
                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.searchProduct(productName, productId, pageNum, pageSize);
    }

    /**
     * 根据分类id查询商品列表
     * @param session 当前会话
     * @param categoryId 分类id
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return 通用服务器响应对象
     */
    @RequestMapping("list_by_categoryId.do")
    @ResponseBody
    public ServerResult getProductListByCategoryId(HttpSession session, Integer categoryId,
                @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        // 获取当前登录用户信息
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            throw new NotLoginException("用户未登录，拒绝访问");
        }
        // 校验用户是否为管理员
        if (user.getRole() != Const.Role.ROLE_ADMIN) {
            throw new AuthorityException("无操作权限");
        }
        // 调用业务层接口执行操作
        return iProductService.getProductByCategoryId(categoryId, pageNum, pageSize);
    }

    /**
     * 富文本中的图片上传
     * @param session 当前会话
     * @param file 待上传的图片
     * @param request 请求
     * @param response 响应
     * @return 通用服务器响应对象
     */
    @RequestMapping(value = "richtext_img_upload.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = Maps.newHashMap();
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "请登录管理员后进行操作");
            return resultMap;
        }
        if (currentUser.getRole() != Const.Role.ROLE_ADMIN) {
            // 填充业务
            //富文本中对于返回值有自己的要求,需按照simditor的要求进行返回
//            {
//                "success": true/false,
//                    "msg": "error message", # optional
//                "file_path": "[real file path]"
//            }
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file, path);
            if (StringUtils.isBlank(targetFileName)) {
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功");
            resultMap.put("file_path", url);
            response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
            return resultMap;
        } else {
            resultMap.put("success", false);
            resultMap.put("msg", "无权限操作");
            return resultMap;
        }
    }
}
